﻿using System;
using System.IO;
using System.Data;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.ComponentModel;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Collections;
using Microsoft.Win32;
using DevExpress.XtraEditors;

namespace FolderBrowserDlg
{
    public partial class CustormOpenFileDialog : Form
    {
        #region Constructor
        public CustormOpenFileDialog()
        {
            InitializeComponent();
        }
        #endregion

        #region Form Load
        private void Form1_Load(object sender, EventArgs e)
        {
            Init();

            FillListView(FolderPath, SpecialFileType.Other);

            InitPictureBox();

            InitMenu();

            InitToolTip();

            //icon
            this.Icon = NetDiskPRJ.Base.BaseForm.ActiveForm.Icon;
        }
        #endregion

        #region Var Def
        /// <summary>
        /// 文件夹的路径
        /// </summary>
        private string FolderPath = "";

        private string fileName = "";
        /// <summary>
        /// 文件路径
        /// </summary>
        public string FileName
        {
            get { return this.fileName; }
        }

        public string[] FileNames
        {
            get { return this.FileNameLst.ToArray(); }
        }

        private bool multiselect = false;

        public bool Multiselect
        {
            set
            {
                this.multiselect = value;
                //用来设置listview 是否可以选中多个文件
                if (multiselect)
                {
                    this.lvFileInfo.MultiSelect = true;
                }
                else
                {
                    this.lvFileInfo.MultiSelect = false;
                }
            }
            get { return this.multiselect; }
        }

        private List<string> FileNameLst = new List<string>();

        /// <summary>
        /// 用来记录上一次打开的文件夹
        /// </summary>
        private List<string> ReturnFolder = new List<string>();

        /// <summary>
        /// 用来记录刚打开时的窗体宽高，当用鼠标拉不的时候，小于这个范围，就不让拉动
        /// </summary>
        private int FrmWidth = 0;
        private int FrmHeight = 0;

        private string filter = "";
        private ImageList ImageLst = new ImageList();
        private SpecialFileType SpeFileType = SpecialFileType.Other;
        #endregion

        #region Init

        private void Init()
        {
            this.tvExplorerInfo.Visible = false;
            FolderPath = Directory.GetCurrentDirectory();
            this.cmbSearchContent.Text = FolderPath.Substring(FolderPath.LastIndexOf("\\") + 1);
            this.cmbSearchContent.Tag = FolderPath;
            this.cmbFileName.Text = "";
            this.cmbFlieType.Text = "";
            this.btnReturn.Enabled = false;

            //肯定还有其它得特殊处理，再测试
            if (FolderPath == Environment.GetFolderPath(Environment.SpecialFolder.Desktop))
            {
                this.btnUpToLastMenu.Enabled = false;
            }
            this.lvFileInfo.Columns.Add("名称", 260);
            this.lvFileInfo.Columns.Add("大小", 70);
            //this.lvFileInfo.Columns.Add("类型");
            this.lvFileInfo.Columns.Add("修改时间", 100);
            FrmWidth = this.Width;
            FrmHeight = this.Height;

            this.cmbFlieType.SelectedIndex = 0;
            this.cmbFlieType.DropDownStyle = ComboBoxStyle.DropDownList;
            this.ImageLst.ColorDepth = ColorDepth.Depth32Bit;
            this.lvFileInfo.LargeImageList = this.ImageLst;
            this.lvFileInfo.SmallImageList = this.ImageLst;
            this.lvFileInfo.TileSize = new System.Drawing.Size(130, 46);

            this.lvFileInfo.View = View.Details;
        }

        /// <summary>
        /// 给各个按钮加夜悬浮内容
        /// </summary>
        private void InitToolTip()
        {
            //这些提示内容要一项一项测试，如果同有此功能就把相应的提示删除掉
            this.toolTip1.SetToolTip(this.btnCreateFolder, "创建新文件夹");
            this.toolTip1.SetToolTip(this.btnDeskTop, "显示在桌面上的文件，文件夹，程序快捷方式和其它项目");
            this.toolTip1.SetToolTip(this.btnFileListView, "查看菜单");
            this.toolTip1.SetToolTip(this.btnMyComputer, "显示连接到此计算机的对口和硬件");
            this.toolTip1.SetToolTip(this.btnMyDocument, "包含信件，报告和其它文档以及文件");
            this.toolTip1.SetToolTip(this.btnMyNetwork, "显示到网站网络计算机和FTP站点的快捷方式");
            this.toolTip1.SetToolTip(this.btnMyRecentDocument, "显示最近打开的文件和文件夹");
            this.toolTip1.SetToolTip(this.btnReturn, "转到访问的上一个文件夹");
            this.toolTip1.SetToolTip(this.btnUpToLastMenu, "向上一级");
        }
        private void InitPictureBox()
        {
            //后退
            //this.btnReturn.Click += new EventHandler(pcMyPictureBox_Click);
            this.btnReturn.Tag = 0x000001;

            //向上
            //this.btnUpToLastMenu.Click += new EventHandler(pcMyPictureBox_Click);
            this.btnUpToLastMenu.Tag = 0x000002;
            //this.btnCreateFolder.Click += new EventHandler(pcMyPictureBox_Click);
            this.btnCreateFolder.Tag = 0x000003;
            //this.btnFileListView.Click += new EventHandler(pcMyPictureBox_Click);
            this.btnFileListView.Tag = 0x000004;
            // this.btnMyRecentDocument.Click += new EventHandler(pcMyPictureBox_Click);
            this.btnMyRecentDocument.Tag = 0x000005;
            // this.btnDeskTop.Click += new EventHandler(pcMyPictureBox_Click);
            this.btnDeskTop.Tag = 0x000006;
            // this.btnMyDocument.Click += new EventHandler(pcMyPictureBox_Click);
            this.btnMyDocument.Tag = 0x000007;
            // this.btnMyComputer.Click += new EventHandler(pcMyPictureBox_Click);
            this.btnMyComputer.Tag = 0x000008;
            //this.btnMyNetwork.Click += new EventHandler(pcMyPictureBox_Click);
            this.btnMyNetwork.Tag = 0x000009;
        }

        private void InitMenu()
        {
            //详细情况
            this.ToolStripDetails.Click += new EventHandler(pcMyPictureBox_Click);
            this.ToolStripDetails.Tag = 0x000010;
            //  this.ToolStripIcons.Click += new EventHandler(pcMyPictureBox_Click);
            //  this.ToolStripIcons.Tag = 0x000011;
            this.ToolStripList.Click += new EventHandler(pcMyPictureBox_Click);
            this.ToolStripList.Tag = 0x000012;
            this.ToolStripThumbnails.Click += new EventHandler(pcMyPictureBox_Click);
            this.ToolStripThumbnails.Tag = 0x000013;
            this.ToolStripTitles.Click += new EventHandler(pcMyPictureBox_Click);
            this.ToolStripTitles.Tag = 0x000014;
        }

        private void GetDesktop(TreeNode rootnode2)
        {
            string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            string path1 = Environment.GetFolderPath(Environment.SpecialFolder.Recent);
            DirectoryInfo[] dis = null;
            DirectoryInfo pdi = new DirectoryInfo(path1);
            try
            {
                dis = pdi.GetDirectories();
                if (dis.Length > 0)
                {
                    foreach (DirectoryInfo di in dis)
                    {
                        TreeNode cnode = new TreeNode();
                        cnode.Text = di.Name;
                        cnode.Name = di.Name;
                        cnode.Tag = di.FullName;
                        rootnode2.Nodes.Add(cnode);
                        cnode.Nodes.Add("");
                    }
                }
                FileInfo[] fis = pdi.GetFiles();
                if (fis.Length > 0)
                {
                    foreach (FileInfo fi in fis)
                    {
                        TreeNode cnode = new TreeNode();
                        cnode.Text = fi.Name;
                        cnode.Name = fi.Name;
                        cnode.Tag = fi.FullName;
                        Icon icon = GetFileIcon(fi.FullName);
                        if (icon != null)
                        {
                            ImageLst.Images.Add(fi.FullName, GetImage(icon));
                            cnode.ImageKey = fi.FullName;
                        }
                        rootnode2.Nodes.Add(cnode);
                    }
                }

            }
            catch { }

        }

        private void InitFillTree(string path, SpecialFileType specialFile)
        {
            this.tvExplorerInfo.ImageList = ImageLst;
            this.tvExplorerInfo.Nodes.Clear();
            this.tvExplorerInfo.Visible = true;

            ///////添加根节点
            TreeNode rootnode = new TreeNode();
            rootnode.Text = "最近使用项目";
            rootnode.Name = "最近使用项目";
            rootnode.Tag = Environment.GetFolderPath(Environment.SpecialFolder.Recent);
            ImageLst.Images.Add(rootnode.Tag.ToString(), ImageIconDirectory.Images[7]);
            rootnode.ImageKey = rootnode.Tag.ToString();
            this.tvExplorerInfo.Nodes.Add(rootnode);
            TreeNode rootnode2 = new TreeNode();
            rootnode2.Text = "桌面";
            rootnode2.Name = "桌面";
            rootnode2.Tag = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            ImageLst.Images.Add(rootnode2.Tag.ToString(), ImageIconDirectory.Images[6]);
            rootnode2.ImageKey = rootnode2.Tag.ToString();
            this.tvExplorerInfo.Nodes.Add(rootnode2);
            rootnode2.Nodes.Add("");
            if (this.tvExplorerInfo.Nodes.Count <= 0)
                this.tvExplorerInfo.Visible = false;

        }

        /// <summary>
        /// 后改的地方
        /// </summary>
        /// <param name="node"></param>
        /// <param name="path"></param>
        private void Getdetails(TreeNode node, string path)////////获取盘下的文件夹以及文件
        {
            this.tvExplorerInfo.ImageList = ImageLst;
            if (node.Nodes.Count != 0)
            {
                node.Nodes.Clear();
            }
            if (node.Text == "桌面")
            {
                if (path == "")
                    return;
                if (!Directory.Exists(path))
                    return;
                string driveName = "";
                string[] folders = path.Split(new string[] { "\\" }, StringSplitOptions.None);
                System.IO.DriveInfo[] allDrives = System.IO.DriveInfo.GetDrives();
                foreach (DriveInfo d in allDrives)
                {

                    string dname = "";
                    try
                    {
                        dname = d.VolumeLabel;
                    }
                    catch
                    {
                        dname = d.Name.Substring(0, 2);
                    }
                    if (dname.Length == 2 || dname == "")
                    {
                        switch (d.DriveType)
                        {
                            case DriveType.Fixed:
                                driveName = "本地磁盘(" + d.Name.Substring(0, 2) + ")";
                                break;
                            case DriveType.Removable:
                                driveName = "可移动磁盘(" + d.Name.Substring(0, 2) + ")";
                                break;
                            case DriveType.CDRom:
                                driveName = "DVD驱动器(" + d.Name.Substring(0, 2) + ")";
                                break;
                            case DriveType.Network:
                                driveName = "网络驱动器(" + d.Name.Substring(0, 2) + ")";
                                break;
                            default:
                                driveName = "未知(" + d.Name.Substring(0, 2) + ")";
                                break;
                        }
                    }
                    else
                    {
                        driveName = dname + "(" + d.Name.Substring(0, 2) + ")";
                    }
                    TreeNode newNode = new TreeNode();
                    newNode.Tag = d.Name;
                    newNode.Name = d.Name;
                    newNode.Text = driveName;
                    Icon icon = GetFileIcon(d.Name);
                    if (icon != null)
                    {
                        ImageLst.Images.Add(d.Name, GetImage(icon));
                        newNode.ImageKey = d.Name;
                    }
                    node.Nodes.Add(newNode);
                    newNode.Nodes.Add("");


                }
            }
            DirectoryInfo[] dis = null;
            DirectoryInfo pdi = new DirectoryInfo(path);
            try
            {
                dis = pdi.GetDirectories();
                if (dis.Length > 0)
                {
                    foreach (DirectoryInfo di in dis)
                    {
                        TreeNode cnode = new TreeNode();
                        cnode.Text = di.Name;
                        cnode.Name = di.Name;
                        cnode.Tag = di.FullName;

                        node.Nodes.Add(cnode);
                        cnode.Nodes.Add("");
                    }
                }
                FileInfo[] fis = pdi.GetFiles();
                if (fis.Length > 0)
                {
                    foreach (FileInfo fi in fis)
                    {
                        TreeNode cnode = new TreeNode();
                        cnode.Text = fi.Name;
                        cnode.Name = fi.Name;
                        cnode.Tag = fi.FullName;
                        Icon icon = GetFileIcon(fi.FullName);
                        if (icon != null)
                        {
                            ImageLst.Images.Add(fi.FullName, GetImage(icon));
                            cnode.ImageKey = fi.FullName;
                        }
                        node.Nodes.Add(cnode);
                    }
                }

            }
            catch { }
        }
        #endregion

        #region Get
        /// <summary>
        /// 得到路径中的最后一个文件夹名字
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private string GetLastFolderName(string path)
        {
            string name = "";
            if (path.EndsWith("\\"))
            {
                path = path.Substring(0, path.Length - 1);
            }
            if (!path.Contains("\\"))
                return path;
            name = path.Substring(path.LastIndexOf("\\") + 1);
            return name == "" ? path : name;
        }

        /// <summary>
        /// 得到当前文件夹的更高一级的文件夹路径
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private string GetSeniorFolderName(string path)
        {
            string name = "";
            if (path.EndsWith("\\"))
            {
                path = path.Substring(0, path.Length - 1);
            }
            if (!path.Contains("\\"))
                return path;
            name = path.Substring(0, path.LastIndexOf("\\"));
            return name == "" ? path : name;
        }

        /// <summary>
        /// 得到ultralistviewitem
        /// </summary>
        /// <returns></returns>
        private ListViewItem GetListViewItem(string text, object tag, string subItem1, string subItem2, string subItem3)
        {
            ListViewItem item = new ListViewItem();
            item.Text = text;
            item.Tag = tag;
            item.SubItems.Add(subItem1);
            // item.SubItems.Add(subItem2);
            item.SubItems.Add(subItem3);
            return item;
        }
        /// <summary>
        /// 将icon转换成image
        /// </summary>
        /// <param name="icon"></param>
        /// <returns></returns>
        private Image GetImage(Icon icon)
        {
            Bitmap bmp = icon.ToBitmap();
            Image image = bmp;
            return image;
        }

        private Image GetImage(DriveType driveType)
        {
            Image image = null;
            switch (driveType)
            {
                case DriveType.CDRom:
                    //image = Resource1.dvd;
                    break;
                case DriveType.Fixed:
                    //image = Resource1.disk;
                    break;
                case DriveType.Removable:
                    //image = Resource1.RemovableDisk;
                    break;
                default:
                    break;
            }
            return image;
        }

        private void GetSubDirectories(string[] folders, TreeNode parentNode, SpecialFileType specialFile)
        {
            if (parentNode.Nodes.Count == 0)
            {
                string path = "";
                TreeNode node = parentNode;
                int no = 0;
                foreach (string name in folders)
                {
                    path += name + "\\";
                    if (no == 0)
                    {
                        no++;
                        continue;
                    }
                    no++;
                    if (Directory.Exists(path))
                    {
                        TreeNode newNode = new TreeNode();
                        newNode.Tag = path;
                        newNode.Text = GetLastFolderName(path);
                        node.Nodes.Add(newNode);
                        node = newNode;
                    }
                }
            }
        }

        private void GetComputerDrives()
        {
            ListViewItem item = null;
            System.IO.DriveInfo[] allDrives = System.IO.DriveInfo.GetDrives();
            foreach (DriveInfo info in allDrives)
            {
                string drivername = info.Name;
                string name = "";
                if (info.IsReady)
                {
                    if (string.IsNullOrEmpty(info.VolumeLabel))
                    {
                        name = "本地磁盘" + "(" + info.Name.Substring(0, info.Name.LastIndexOf("\\")) + ")";
                    }
                    else
                    {

                        name = info.VolumeLabel + "(" + info.Name.Substring(0, info.Name.LastIndexOf("\\")) + ")";
                    }
                }
                else
                {

                    name = info.DriveType + "(" + info.Name.Substring(0,info.Name.LastIndexOf("\\")) + ")";
                }

                item = GetListViewItem(GetLastFolderName(name), drivername, "", "文件夹", "磁盘");
                lvFileInfo.Items.Add(item);

                Icon icon = GetFileIcon(info.Name);
                if (icon != null)
                {
                    ImageLst.Images.Add(name, GetImage(icon));
                    item.ImageKey = name;

                }
            }
        }


        /// <summary>
        /// 得到文件的大小
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        private string GetFileLength(long length)
        {
            decimal decLen = System.Math.Ceiling((decimal)length / (decimal)1024);
            return decLen.ToString() + "K";
        }

        /// <summary>
        /// 得到文件夹的大小
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        private long GetFolderLength(DirectoryInfo info)
        {
            long totalLen = 0;
            FileInfo[] files = info.GetFiles();

            foreach (FileInfo fileInfo in files)
            {
                totalLen += fileInfo.Length;
            }
            DirectoryInfo[] dirs = info.GetDirectories();

            foreach (DirectoryInfo dir in dirs)
            {
                totalLen += GetFolderLength(dir);
            }
            return totalLen;
        }

        private void GetDriveName()//////参数DriveInfo info
        {
            DriveInfo[] dr = DriveInfo.GetDrives();
            string driveName = "";
            foreach (DriveInfo d in dr)
            {
                switch (d.DriveType)
                {
                    case DriveType.Fixed:
                        driveName = "本地磁盘(" + d.Name.Substring(0, 2) + ")";
                        break;
                    case DriveType.Removable:
                        driveName = "可移动磁盘(" + d.Name.Substring(0, 2) + ")";
                        break;
                    case DriveType.CDRom:
                        driveName = "DVD驱动器(" + d.Name.Substring(0, 2) + ")";
                        break;
                    case DriveType.Network:
                        driveName = "网络驱动器(" + d.Name.Substring(0, 2) + ")";
                        break;
                    default:
                        driveName = "未知(" + d.Name + ")";
                        break;
                }
                this.tvExplorerInfo.Nodes.Add(d.Name, driveName);
            }
        }


        /// 获取文件图标 
        /// </summary>
        /// <param name="p_Path">文件全路径</param>
        /// <returns>图标</returns>
        private Icon GetFileIcon(string p_Path)
        {
            SHFILEINFO _SHFILEINFO = new SHFILEINFO();
            IntPtr _IconIntPtr = SHGetFileInfo(p_Path, 0, ref _SHFILEINFO, (uint)Marshal.SizeOf(_SHFILEINFO), (uint)(SHGFI.SHGFI_ICON | SHGFI.SHGFI_LARGEICON | SHGFI.SHGFI_USEFILEATTRIBUTES));
            if (_IconIntPtr.Equals(IntPtr.Zero)) return null;
            Icon _Icon = System.Drawing.Icon.FromHandle(_SHFILEINFO.hIcon);
            return _Icon;
        }
        /// <summary>
        /// 获取文件夹图标  
        /// </summary>
        /// <returns>图标</returns>
        private Icon GetDirectoryIcon()
        {
            SHFILEINFO _SHFILEINFO = new SHFILEINFO();
            IntPtr _IconIntPtr = SHGetFileInfo(@"", 0, ref _SHFILEINFO, (uint)Marshal.SizeOf(_SHFILEINFO), (uint)(SHGFI.SHGFI_ICON | SHGFI.SHGFI_LARGEICON));
            if (_IconIntPtr.Equals(IntPtr.Zero)) return null;
            Icon _Icon = System.Drawing.Icon.FromHandle(_SHFILEINFO.hIcon);
            return _Icon;
        }

        private Icon GetLocalDiskIcon()
        {
            SHFILEINFO _SHFILEINFO = new SHFILEINFO();
            IntPtr _IconIntPtr = SHGetFileInfo(@"", 0, ref _SHFILEINFO, (uint)Marshal.SizeOf(_SHFILEINFO), (uint)(SHGFI.SHGFI_ICON | SHGFI.SHGFI_LARGEICON | SHGFI.SHGFI_SHEELICONSIZE));
            if (_IconIntPtr.Equals(IntPtr.Zero)) return null;
            Icon _Icon = System.Drawing.Icon.FromHandle(_SHFILEINFO.hIcon);
            return _Icon;
        }

        private string GetTypeName(string fileName)
        {
            FileInfomation fileInfo = new FileInfomation();   //初始化FileInfomation结构
            int res = GetFileInfo(fileName, (int)FileAttributeFlags.FILE_ATTRIBUTE_NORMAL,
                ref fileInfo, Marshal.SizeOf(fileInfo), (int)(GetFileInfoFlags.SHGFI_TYPENAME));
            return fileInfo.szTypeName;
        }

        /// <summary>
        /// 生成ULTRALISTVIEWGROUP
        /// </summary>
        /// <param name="name"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        private ListViewGroup GetListViewGroup(string name, string key)
        {
            ListViewGroup group = new ListViewGroup(name);
            return group;
        }
        #endregion

        #region Fill
        private void FillListView(string path, SpecialFileType specialFile)
        {
            if (path == "我的电脑")
                specialFile = SpecialFileType.MyComputer;

            if (string.IsNullOrEmpty(path) && specialFile != SpecialFileType.MyComputer)
                return;

            if (!Directory.Exists(path) && specialFile != SpecialFileType.MyComputer)
                return;

            ListViewItem item = null;
            this.FolderPath = specialFile != SpecialFileType.MyComputer ? path : "我的电脑";
            string text = FillFileContentCmb(specialFile);
            this.cmbSearchContent.Text = text == "" ? GetLastFolderName(path) : text;
            this.cmbSearchContent.Tag = specialFile == SpecialFileType.MyComputer ? "我的电脑" : path;

            lvFileInfo.Items.Clear();
            this.ImageLst.Images.Clear();
            DirectoryInfo dirInfo = null;
            if (specialFile != SpecialFileType.MyComputer)
            {
                if (!path.EndsWith("\\"))
                {
                    path += "\\";
                }
                dirInfo = new DirectoryInfo(path);
            }
            else
            {
                GetComputerDrives();
                return;
            }

            DirectoryInfo[] dirInfos = dirInfo.GetDirectories();
            System.IO.DriveInfo[] allDrives = System.IO.DriveInfo.GetDrives();
            foreach (DirectoryInfo info in dirInfos)
            {

                FileAttributes finfo = info.Attributes & FileAttributes.Hidden;
                if (finfo == FileAttributes.Hidden)
                {
                    continue;
                }
                finfo = info.Attributes & FileAttributes.System;
                if (finfo == FileAttributes.System)
                {
                    continue;
                }
                string name = info.FullName;
                item = GetListViewItem(GetLastFolderName(name), name, "", "文件夹", info.LastWriteTime.ToString());
                lvFileInfo.Items.Add(item);

                Icon icon = GetDirectoryIcon();
                if (icon != null)
                {
                    ImageLst.Images.Add(name, GetImage(icon));
                    item.ImageKey = name;

                }
            }

            FileInfo[] fileInfos = dirInfo.GetFiles();
            foreach (FileInfo info in fileInfos)
            {
                FileAttributes finfo = info.Attributes & FileAttributes.Hidden;
                if (finfo == FileAttributes.Hidden)
                {
                    continue;
                }
                finfo = info.Attributes & FileAttributes.System;
                if (finfo == FileAttributes.System)
                {
                    continue;
                }
                string name = info.FullName;

                if (filter != "所有文件(*.*)")
                {
                    if (!filter.ToUpper().Contains(Path.GetExtension(name).ToUpper()))
                    {
                        continue;
                    }
                }

                //1-将“\\”去掉
                string itemText = (SpecialFileType.MyComputer == specialFile) ? name
                : (File.Exists(name) ? Path.GetFileName(name) : name.Substring(name.LastIndexOf("\\") + 1));

                item = GetListViewItem(itemText, name, GetFileLength(info.Length), "fileTypeName", info.LastWriteTime.ToString());
                Icon icon = GetFileIcon(name);
                if (icon != null)
                {
                    ImageLst.Images.Add(name, GetImage(icon));
                    item.ImageKey = name;
                }
                this.lvFileInfo.Items.Add(item);
            }
        }

        private string FillFileContentCmb(SpecialFileType specialType)
        {
            string name = "";
            switch (specialType)
            {
                case SpecialFileType.DeskTop:
                    name = "桌面";
                    break;
                case SpecialFileType.MyComputer:
                    name = "我的电脑";
                    break;
                case SpecialFileType.MyDocument:
                    name = "我的文档";
                    break;
                case SpecialFileType.NetWork:
                    name = "网上邻居";
                    break;
                case SpecialFileType.RecentDocument:
                    name = "我最近的文档";
                    break;
                default:
                    break;
            }
            return name;
        }
        #endregion

        #region Add
        private void AddUltraListviewGroup()
        {
            this.lvFileInfo.Groups.Clear();
            ListViewGroup group = GetListViewGroup("磁盘", "磁盘");
            if (!lvFileInfo.Groups.Contains(group))
            {
                lvFileInfo.Groups.Add(group);
            }

            group = GetListViewGroup("有可移动存储的设备", "有可移动存储的设备");
            if (!lvFileInfo.Groups.Contains(group))
            {
                lvFileInfo.Groups.Add(group);
            }

            group = GetListViewGroup("在这台计算机上存储的文件", "在这台计算机上存储的文件");
            if (!lvFileInfo.Groups.Contains(group))
            {
                lvFileInfo.Groups.Add(group);
            }
        }

        private void AddUltraListviewGroup(DriveType deviceType, ListViewItem item)
        {
            switch (deviceType)
            {
                case DriveType.Fixed:
                    break;
                case DriveType.CDRom:
                case DriveType.Ram:
                case DriveType.Removable:
                case DriveType.Unknown:
                    break;
                case DriveType.Network:
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 新建文件夹后，将新建的文件夹显示到listview里边
        /// </summary>
        /// <param name="newFolder"></param>
        /// <param name="value"></param>
        private void AddNewListViewItem(string newFolder, string value)
        {
            ListViewItem item = new ListViewItem();
            item.Text = newFolder;
            item.Tag = value;
            DirectoryInfo info = new DirectoryInfo(value);
            item.SubItems.Add("");
            item.SubItems.Add("文件夹");
            item.SubItems.Add(info.LastWriteTime.ToString());
            Icon icon = GetDirectoryIcon();

            if (icon != null)
            {
                ImageLst.Images.Add(value, icon);
                item.ImageKey = value;
            }
            if (!lvFileInfo.Items.Contains(item))
            {
                lvFileInfo.Items.Add(item);

                item.Selected = true;
            }
        }
        #endregion

        #region 控件操作
        private void lvInfo_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.lvFileInfo.SelectedItems == null || this.lvFileInfo.SelectedItems.Count < 0)
                return;
            this.lvInfo_MouseClick(sender, null);
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.fileName = "";
            this.FileNameLst.Clear();
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            FileNameLst = new List<string>();
            FileNameLst.Clear();

            bool isHasFolder = false;
            fileName = "";
            FolderPath = "";
            //取得文件夹或者文件的路径 
            foreach (ListViewItem item in this.lvFileInfo.SelectedItems)
            {
                string pathName = (string)item.Tag;
                if (File.Exists(pathName))
                {
                    if (fileName == "")
                    {
                        fileName = pathName;
                    }
                    FileNameLst.Add(pathName);
                }

                if (Directory.Exists(pathName))
                {
                    if (FolderPath == "")
                    {
                        FolderPath = pathName;
                    }
                    FileNameLst.Add(pathName);
                    //  isHasFolder = true;
                    //  break;
                }
            }

            if (FileNameLst.Count > 0)
            {
                this.DialogResult = DialogResult.OK;
                this.Close();
            }

            if (isHasFolder)
            {
                FillListView(FolderPath, SpecialFileType.Other);
            }
        }

        /// <summary>
        /// true 表示已经添加过 false　表示没有添加过
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private bool CheckReturnFolderIsHaveAdded(string path)
        {
            if (this.ReturnFolder.Count > 0)
            {
                return this.ReturnFolder[this.ReturnFolder.Count - 1] == path;
            }
            return false;
        }

        private void pcMyPictureBox_Click(object sender, EventArgs e)
        {
            this.tvExplorerInfo.Visible = false;
            this.cmbFileName.Text = "";
            object obj = null;

            if (sender is Button)
            {
                obj = ((Button)sender).Tag;
            }

            if (sender is ToolStripMenuItem)
            {
                obj = ((ToolStripMenuItem)sender).Tag;
            }

            if (obj == null)
                return;

            int clickTag = Convert.ToInt32(obj);
            string path = FolderPath;
            switch (clickTag)
            {
                //后退
                case 0x000001:
                    if (this.ReturnFolder.Count > 0)
                    {
                        path = this.ReturnFolder[this.ReturnFolder.Count - 1];
                        SpeFileType = SpecialFileType.Other;
                        FillListView(path, SpecialFileType.Other);
                        this.ReturnFolder.RemoveAt(this.ReturnFolder.Count - 1);
                    }
                    break;
                //向上
                case 0x000002:

                    if (FolderPath == Environment.GetFolderPath(Environment.SpecialFolder.Desktop))
                    {
                        this.btnUpToLastMenu.Enabled = false;
                        return;
                    }

                    path = GetSeniorFolderName(FolderPath);

                    if (FolderPath == "我的电脑")
                    {
                        SpeFileType = SpecialFileType.DeskTop;
                        path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                        FillListView(path, SpecialFileType.DeskTop);
                        break;
                    }
                    //true 表明已经退到C: E:这样的路径上了
                    if (CheckPathIsDrive(path))
                    {
                        SpeFileType = SpecialFileType.MyComputer;
                        FillListView(path, SpecialFileType.MyComputer);
                    }
                    else
                    {
                        SpeFileType = SpecialFileType.Other;
                        FillListView(path, SpecialFileType.Other);
                    }
                    break;
                //创建新文件夹
                case 0x000003:
                    string newFolder = "新建文件夹";

                    if (path == "")
                        return;
                    string fullPath = path + "\\" + newFolder;
                    if (Directory.Exists(fullPath))
                    {
                        for (int i = 1; i <= int.MaxValue; i++)
                        {
                            if (!Directory.Exists(fullPath + "(" + i + ")"))
                            {
                                fullPath = fullPath + "(" + i + ")";
                                newFolder += "(" + i + ")";
                                Directory.CreateDirectory(fullPath);
                                AddNewListViewItem(newFolder, fullPath);
                                break;
                            }
                        }
                    }
                    else
                    {
                        Directory.CreateDirectory(fullPath);
                        AddNewListViewItem(newFolder, fullPath);
                    }
                    break;
                //文件排列方式
                case 0x000004:
                    this.contextMenuStrip1.Show(Cursor.Position);
                    break;
                //最近的文件
                case 0x000005:
                    SpeFileType = SpecialFileType.RecentDocument;
                    path = Environment.GetFolderPath(Environment.SpecialFolder.Recent);
                    FillListView(path, SpecialFileType.RecentDocument);
                    break;
                //桌面
                case 0x000006:
                    SpeFileType = SpecialFileType.DeskTop;
                    path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                    FillListView(path, SpecialFileType.DeskTop);
                    break;
                //我的文档
                case 0x000007:
                    SpeFileType = SpecialFileType.MyDocument;
                    path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                    FillListView(path, SpecialFileType.MyDocument);
                    break;
                //我的电脑
                case 0x000008:
                    SpeFileType = SpecialFileType.MyComputer;
                    path = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer);
                    path = System.Environment.GetEnvironmentVariable("COMPUTERNAME");
                    FillListView(path, SpecialFileType.MyComputer);
                    break;
                //网上邻居
                case 0x000009:
                    RegistryKey folders;
                    folders = OpenRegistryPath(Registry.CurrentUser, @"\software\microsoft\windows\currentversion\explorer\shell folders");
                    path = folders.GetValue("Nethood").ToString();
                    SpeFileType = SpecialFileType.NetWork;
                    FillListView(path, SpecialFileType.NetWork);
                    break;

                //文件排列：详细
                case 0x000010:
                    this.lvFileInfo.View = View.Details;
                    break;
                //文件排列：图标
                case 0x000011:
                    this.lvFileInfo.View = View.SmallIcon;
                    break;
                //文件排列：列表
                case 0x000012:
                    this.lvFileInfo.View = View.List;
                    break;
                //文件排列：缩略图
                case 0x000013:
                    this.lvFileInfo.View = View.LargeIcon;
                    break;
                //文件排列：平铺
                case 0x000014:
                    this.lvFileInfo.View = View.Tile;
                    break;
                default:
                    break;
            }

        }

        private RegistryKey OpenRegistryPath(RegistryKey root, string s)
        {
            s = s.Remove(0, 1) + @"\";
            while (s.IndexOf(@"\") != -1)
            {
                root = root.OpenSubKey(s.Substring(0, s.IndexOf(@"\")));
                s = s.Remove(0, s.IndexOf(@"\") + 1);
            }
            return root;
        }

        /// <summary>
        /// 查看路径是不是本地磁盘了 
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private bool CheckPathIsDrive(string path)
        {
            if (!path.EndsWith("\\"))
            {
                path += "\\";
            }

            foreach (string info in Environment.GetLogicalDrives())
            {
                if (info == path)
                    return true;
            }
            return false;
        }

        private void lvInfo_MouseClick(object sender, MouseEventArgs e)
        {
            if (this.lvFileInfo.SelectedItems == null || this.lvFileInfo.SelectedItems.Count < 0)
                return;

            this.FileNameLst.Clear();
            if (this.lvFileInfo.SelectedItems.Count > 0)
            {
                this.cmbFileName.Text = "";
                int index = 0;
                string pathName = "";

                for (int i = 0; i < this.lvFileInfo.SelectedItems.Count; i++)
                {
                    pathName = (string)this.lvFileInfo.SelectedItems[i].Tag;
                    if (!File.Exists(pathName))
                        continue;

                    if (index != 0)
                    {
                        this.cmbFileName.Text += ";";
                    }

                    this.cmbFileName.Text += Path.GetFileName(pathName);
                    this.FileNameLst.Add(pathName);
                    index++;

                }

            }
        }

        private void cmbSearchContent_TextChanged(object sender, EventArgs e)
        {
            InitFillTree((string)this.cmbSearchContent.Tag, SpecialFileType.Other);
        }

        private void procTimer_Tick(object sender, EventArgs e)
        {
            if (!this.cmbSearchContent.Focused)
            {
                if (!this.tvExplorerInfo.Focused)
                    this.tvExplorerInfo.Visible = false;
            }

            this.btnReturn.Enabled = this.ReturnFolder.Count > 0 ? true : false;
            this.btnUpToLastMenu.Enabled = (FolderPath == Environment.GetFolderPath(Environment.SpecialFolder.Desktop)) ? false : true;
            this.btnCreateFolder.Enabled = (FolderPath == "") ? false : true;

        }

        private void cmbSearchContent_ValueChanged(object sender, EventArgs e)
        {
            if (this.cmbSearchContent.Tag == null)
                return;

            if (!CheckReturnFolderIsHaveAdded((string)this.cmbSearchContent.Tag))
            {
                this.ReturnFolder.Add((string)this.cmbSearchContent.Tag);
            }
        }

        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {

        }

        private void lvFileInfo_KeyDown(object sender, KeyEventArgs e)
        {

        }

        private void lvFileInfo_KeyUp(object sender, KeyEventArgs e)
        {
            lvInfo_MouseClick(sender, null);
        }

        private void lvFileInfo_MouseDown(object sender, MouseEventArgs e)
        {

        }
        #endregion

        #region 获取系统文件信息
        //系统文件图标信息
        [StructLayout(LayoutKind.Sequential)]
        private struct SHFILEINFO
        {
            public IntPtr hIcon;
            public IntPtr iIcon;
            public uint dwAttributes;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
            public string szDisplayName;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
            public string szTypeName;
        }

        private enum SHGFI
        {
            SHGFI_ICON = 0x100,
            SHGFI_LARGEICON = 0x0,
            SHGFI_USEFILEATTRIBUTES = 0x10,
            SHGFI_SHEELICONSIZE = 0X04,
            SHGFI_SMALLICON = 0x0
        }

        //定义SHFILEINFO结构
        [StructLayout(LayoutKind.Sequential)]
        private struct FileInfomation
        {
            public IntPtr hIcon;
            public int iIcon;
            public int dwAttributes;

            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
            public string szDisplayName;

            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
            public string szTypeName;
        }
        #endregion

        #region Enum
        //定义文件属性标识
        private enum FileAttributeFlags : int
        {
            FILE_ATTRIBUTE_READONLY = 0x00000001,
            FILE_ATTRIBUTE_HIDDEN = 0x00000002,
            FILE_ATTRIBUTE_SYSTEM = 0x00000004,
            FILE_ATTRIBUTE_DIRECTORY = 0x00000010,
            FILE_ATTRIBUTE_ARCHIVE = 0x00000020,
            FILE_ATTRIBUTE_DEVICE = 0x00000040,
            FILE_ATTRIBUTE_NORMAL = 0x00000080,
            FILE_ATTRIBUTE_TEMPORARY = 0x00000100,
            FILE_ATTRIBUTE_SPARSE_FILE = 0x00000200,
            FILE_ATTRIBUTE_REPARSE_POINT = 0x00000400,
            FILE_ATTRIBUTE_COMPRESSED = 0x00000800,
            FILE_ATTRIBUTE_OFFLINE = 0x00001000,
            FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = 0x00002000,
            FILE_ATTRIBUTE_ENCRYPTED = 0x00004000
        }

        //定义获取资源标识
        private enum GetFileInfoFlags : int
        {
            SHGFI_ICON = 0x000000100,     // get icon
            SHGFI_DISPLAYNAME = 0x000000200,     // get display name
            SHGFI_TYPENAME = 0x000000400,     // get type name
            SHGFI_ATTRIBUTES = 0x000000800,     // get attributes
            SHGFI_ICONLOCATION = 0x000001000,     // get icon location
            SHGFI_EXETYPE = 0x000002000,     // return exe type
            SHGFI_SYSICONINDEX = 0x000004000,     // get system icon index
            SHGFI_LINKOVERLAY = 0x000008000,     // put a link overlay on icon
            SHGFI_SELECTED = 0x000010000,     // show icon in selected state
            SHGFI_ATTR_SPECIFIED = 0x000020000,     // get only specified attributes
            SHGFI_LARGEICON = 0x000000000,     // get large icon
            SHGFI_SMALLICON = 0x000000001,     // get small icon
            SHGFI_OPENICON = 0x000000002,     // get open icon
            SHGFI_SHELLICONSIZE = 0x000000004,     // get shell size icon
            SHGFI_PIDL = 0x000000008,     // pszPath is a pidl
            SHGFI_USEFILEATTRIBUTES = 0x000000010,     // use passed dwFileAttribute
            SHGFI_ADDOVERLAYS = 0x000000020,     // apply the appropriate overlays
            SHGFI_OVERLAYINDEX = 0x000000040       // Get the index of the overlay
        }

        /// <summary>
        /// 特殊文件类型
        /// </summary>
        public enum SpecialFileType
        {
            MyComputer,
            NetWork,
            DeskTop,
            MyDocument,
            RecentDocument,
            Other
        }
        #endregion

        #region DllImport
        /// <summary>
        /// 返回系统设置的图标
        /// </summary>
        /// <param name="pszPath">文件路径 如果为""  返回文件夹的</param>
        /// <param name="dwFileAttributes">0</param>
        /// <param name="psfi">结构体</param>
        /// <param name="cbSizeFileInfo">结构体大小</param>
        /// <param name="uFlags">枚举类型</param>
        /// <returns>-1失败</returns>
        [DllImport("shell32.dll")]
        private static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref   SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);

        //在shell32.dll导入函数SHGetFileInfo
        [DllImport("shell32.dll", EntryPoint = "SHGetFileInfo")]
        private static extern int GetFileInfo(string pszPath, int dwFileAttributes,
             ref FileInfomation psfi, int cbFileInfo, int uFlags);
        #endregion

        private void tvExplorerInfo_AfterSelect(object sender, TreeViewEventArgs e)
        {
            this.tvExplorerInfo.Visible = false;
            if (this.tvExplorerInfo.SelectedNode == null)
                return;

            FillListView((string)this.tvExplorerInfo.SelectedNode.Tag, SpecialFileType.Other);
        }

        private void cmbFlieType_TextChanged(object sender, EventArgs e)
        {
            filter = this.cmbFlieType.Text;
            FillListView(FolderPath, SpeFileType);
        }

        private void listView1_DoubleClick(object sender, EventArgs e)
        {
            // this.btnOK.PerformClick();
            FileNameLst = new List<string>();
            FileNameLst.Clear();

            bool isHasFolder = false;
            fileName = "";
            FolderPath = "";
            //取得文件夹或者文件的路径 
            foreach (ListViewItem item in this.lvFileInfo.SelectedItems)
            {
                string pathName = (string)item.Tag;
                if (File.Exists(pathName))
                {
                    if (fileName == "")
                    {
                        fileName = pathName;
                    }
                    FileNameLst.Add(pathName);
                }

                if (Directory.Exists(pathName))
                {
                    if (FolderPath == "")
                    {
                        FolderPath = pathName;
                    }
                    // FileNameLst.Add(pathName);
                    isHasFolder = true;
                    break;
                }
            }

            //if (FileNameLst.Count > 0)
            //{
            //    MessageBox.Show(string.Join(",", FileNameLst.ToArray()));
            //    this.DialogResult = DialogResult.OK;
            //    this.Close();
            //}

            if (isHasFolder)
            {
                FillListView(FolderPath, SpecialFileType.Other);
            }
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void tvExplorerInfo_AfterExpand(object sender, TreeViewEventArgs e)
        {

        }

        private void tvExplorerInfo_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            Getdetails(e.Node, e.Node.Tag.ToString());
        }

        private void dkToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // this.btnOK.PerformClick();
            FileNameLst = new List<string>();
            FileNameLst.Clear();

            bool isHasFolder = false;
            fileName = "";
            FolderPath = "";
            //取得文件夹或者文件的路径 
            foreach (ListViewItem item in this.lvFileInfo.SelectedItems)
            {
                string pathName = (string)item.Tag;
                if (File.Exists(pathName))
                {
                    if (fileName == "")
                    {
                        fileName = pathName;
                    }
                    FileNameLst.Add(pathName);
                }

                if (Directory.Exists(pathName))
                {
                    if (FolderPath == "")
                    {
                        FolderPath = pathName;
                    }
                    // FileNameLst.Add(pathName);
                    isHasFolder = true;
                    break;
                }
            }

            //if (FileNameLst.Count > 0)
            //{
            //    MessageBox.Show(string.Join(",", FileNameLst.ToArray()));
            //    this.DialogResult = DialogResult.OK;
            //    this.Close();
            //}

            if (isHasFolder)
            {
                FillListView(FolderPath, SpecialFileType.Other);
            }
        }

        private void cmmToolStripMenuItem_Click(object sender, EventArgs e)
        {

            if (lvFileInfo.SelectedItems.Count > 0)
            {

                lvFileInfo.LabelEdit = true;
                lvFileInfo.SelectedItems[0].BeginEdit();
            }
            else
            {

                XtraMessageBox.Show("请先选择文件");
            }
           

        }

        private void lvFileInfo_AfterLabelEdit(object sender, LabelEditEventArgs e)
        {
            if (!string.IsNullOrEmpty(e.Label))
            {
                //取得原文件和文件夹名
                string fullpath = lvFileInfo.SelectedItems[0].Tag.ToString();
                string pathwithoutfoldername = fullpath.Substring(0, fullpath.LastIndexOf("\\") + 1);
                string newfolername = e.Label.ToString();
                string newfullpath = pathwithoutfoldername + newfolername;
                //为文件夹
                if (Directory.Exists(fullpath))
                {
                    Directory.Move(fullpath, newfullpath);
                }
                //为文件
                if (File.Exists(fullpath))
                {
                    FileInfo fi = new FileInfo(fullpath);
                    fi.MoveTo(newfullpath);
                }
                FillListView(FolderPath, SpecialFileType.Other);
            }

        }

        private void filecopyfz(object sender, EventArgs e)
        {
            string fullpathall = "copy,";
            foreach (ListViewItem it in lvFileInfo.SelectedItems)
            {
                fullpathall += it.Tag.ToString() + ",";
            }
            Clipboard.Clear();//清空剪切板内容 
            Clipboard.SetData(DataFormats.Text, fullpathall);//复制内容到剪切板
        }

        private void pastnt(object sender, EventArgs e)
        {
            IDataObject iData = Clipboard.GetDataObject();
            if (iData.GetDataPresent(DataFormats.Text))
            {//如果剪贴板中的数据是文本格式
                string frompath = iData.GetData(DataFormats.Text).ToString();
                //获取所有文件和文件夹列表
                string[] pathlist = frompath.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                List<string> files = new List<string>();
                List<string> dirs = new List<string>();
                foreach (string s in pathlist)
                {
                    if (File.Exists(s))
                    {
                        files.Add(s);
                    }
                    if (Directory.Exists(s))
                    {
                        dirs.Add(s);
                    }
                }
                foreach (string s in dirs)
                {
                    if (Directory.Exists(s))
                    {
                        string destpath = this.FolderPath + "\\";
                        if (!CheckFileAndDir(s, destpath))
                        {
                            MessageBox.Show("已存在同名文件不能粘贴");
                            return;
                        }
                    }
                }
                foreach (string s in files)
                {

                    if (File.Exists(s))
                    {
                        string destpath = this.FolderPath + "\\" + Path.GetFileName(s);
                        if (File.Exists(destpath))
                        {
                            MessageBox.Show("已存在同名文件不能粘贴");
                            return;
                        }

                    }
                }
                foreach (string s in pathlist)
                {
                    if (File.Exists(s))
                    {
                        string destpath = this.FolderPath + "\\" + Path.GetFileName(s);
                        if (File.Exists(destpath))
                        {
                            MessageBox.Show("已存在同名文件不能粘贴");
                            return;
                        }
                        File.Copy(s, destpath);
                    }
                    if (Directory.Exists(s))
                    {
                        string destpath = this.FolderPath + "\\";
                        if (CheckFileAndDir(s, destpath))
                        {
                            CopyDirectory(s, destpath);
                        }
                        else
                        {
                            MessageBox.Show("已存在同名文件不能粘贴");
                            return;
                        }


                    }
                }
                if (frompath.Split(',')[0] == "cut")
                {
                    foreach (string s in dirs)
                    {
                        if (Directory.Exists(s))
                        {
                            string destpath = this.FolderPath + "\\";

                            Directory.Delete(s, true);
                        }
                    }
                    foreach (string s in files)
                    {

                        if (File.Exists(s))
                        {
                            string destpath = this.FolderPath + "\\" + Path.GetFileName(s);
                            if (File.Exists(destpath))
                            {
                                File.Delete(s);

                            }

                        }
                    }

                }
                FillListView(FolderPath, SpecialFileType.Other);
            }
            else
            {
                MessageBox.Show("目前剪贴板中数据不可转换为文本", "错误");
            }
        }
        /// <summary>
        /// 检查文件和文件夹
        /// </summary>
        /// <param name="srcdir">源路径</param>
        /// <param name="desdir">目标路径</param>
        /// <returns></returns>
        private bool CheckFileAndDir(string srcdir, string desdir)
        {

            string folderName = srcdir.Substring(srcdir.LastIndexOf("\\") + 1);
            string desfolderdir = desdir + "\\" + folderName;
            if (desdir.LastIndexOf("\\") == (desdir.Length - 1))
            {
                desfolderdir = desdir + folderName;
            }
            string[] filenames = Directory.GetFileSystemEntries(srcdir);
            foreach (string file in filenames)// 遍历所有的文件和目录         
            {
                if (Directory.Exists(file))// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件      
                {
                    string currentdir = desfolderdir + "\\" + file.Substring(file.LastIndexOf("\\") + 1);
                    if (Directory.Exists(currentdir))
                    {
                        CheckFileAndDir(file, desfolderdir);
                    }
                }
                if (File.Exists(file))
                {
                    string srcfileName = file.Substring(file.LastIndexOf("\\") + 1);
                    srcfileName = desfolderdir + "\\" + srcfileName;
                    if (File.Exists(srcfileName))
                    {
                        return false;
                    }
                }
            }
            return true;
        }
        private void CopyDirectory(string srcdir, string desdir)
        {
            string folderName = srcdir.Substring(srcdir.LastIndexOf("\\") + 1);
            string desfolderdir = desdir + "\\" + folderName;
            if (desdir.LastIndexOf("\\") == (desdir.Length - 1))
            {
                desfolderdir = desdir + folderName;
            }
            string[] filenames = Directory.GetFileSystemEntries(srcdir);
            foreach (string file in filenames)// 遍历所有的文件和目录         
            {
                if (Directory.Exists(file))// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件      
                {
                    string currentdir = desfolderdir + "\\" + file.Substring(file.LastIndexOf("\\") + 1);
                    if (!Directory.Exists(currentdir))
                    {
                        Directory.CreateDirectory(currentdir);
                    }
                    CopyDirectory(file, desfolderdir);
                }
                else // 否则直接copy文件       
                {
                    string srcfileName = file.Substring(file.LastIndexOf("\\") + 1);
                    srcfileName = desfolderdir + "\\" + srcfileName;
                    if (!Directory.Exists(desfolderdir))
                    {
                        Directory.CreateDirectory(desfolderdir);
                    }
                    File.Copy(file, srcfileName);
                }
            }
        }

        private void filecut(object sender, EventArgs e)
        {
            string fullpathall = "cut,";
            foreach (ListViewItem it in lvFileInfo.SelectedItems)
            {
                fullpathall += it.Tag.ToString() + ",";
            }
            Clipboard.Clear();//清空剪切板内容 
            Clipboard.SetData(DataFormats.Text, fullpathall);//复制内容到剪切板
        }

        private void quxiao(object sender, EventArgs e)
        {
            contextMenuStrip2.Hide();
        }

        private void shanchu(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要删除吗", "确认", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {


                foreach (ListViewItem it in lvFileInfo.SelectedItems)
                {
                    string s = it.Tag.ToString();

                    if (Directory.Exists(s))
                    {
                        string destpath = this.FolderPath + "\\";

                        Directory.Delete(s, true);
                    }



                    if (File.Exists(s))
                    {
                        string destpath = this.FolderPath + "\\" + Path.GetFileName(s);
                        if (File.Exists(destpath))
                        {
                            File.Delete(s);

                        }

                    }

                }
                FillListView(FolderPath, SpecialFileType.Other);
            }
        }
    }
}
